import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class UnderlineTabIndicatorCustom extends Decoration {
  const UnderlineTabIndicatorCustom({
    required this.indicatorWidth,
    this.shape = StrokeCap.round,
    this.insets = EdgeInsets.zero,
    this.borderSide = const BorderSide(
      width: 2.5,
      color: Colors.red,
    ),
  });

  final double indicatorWidth; // 宽度
  final StrokeCap shape; // 圆角 ｜ 直角
  final EdgeInsetsGeometry insets; // 位置
  final BorderSide borderSide; // 颜色、高度

  @override
  _UnderlinePainter createBoxPainter([VoidCallback? onChanged]) {
    return _UnderlinePainter(this, onChanged!, 40);
  }
}

class _UnderlinePainter extends BoxPainter {
  _UnderlinePainter(this.decoration, VoidCallback onChanged, lineWidth)
      : super(onChanged);

  final UnderlineTabIndicatorCustom decoration;
  BorderSide get borderSide => decoration.borderSide;
  EdgeInsetsGeometry get insets => decoration.insets;

  Rect _indicatorRectFor(Rect rect, TextDirection textDirection) {
    final Rect indicator = insets.resolve(textDirection).deflateRect(rect);
    // 指示器宽度
    double indicatorWidth = decoration.indicatorWidth;
    // 取中间坐标
    double cw = (indicator.left + indicator.right) / 2;
    return Rect.fromLTWH(
      cw - indicatorWidth / 2,
      indicator.bottom - borderSide.width,
      indicatorWidth,
      borderSide.width,
    );
  }

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    assert(configuration.size != null);
    final Rect rect = offset & configuration.size!;
    final TextDirection textDirection = configuration.textDirection!;
    final Rect indicator = _indicatorRectFor(rect, textDirection).deflate(
      borderSide.width / 2.0,
    );
    // 圆角
    final Paint paint = borderSide.toPaint()..strokeCap = decoration.shape;
    canvas.drawLine(indicator.bottomLeft, indicator.bottomRight, paint);
  }
}
